import 'package:flutter/material.dart';
import 'package:yp/config/index.dart';
import 'package:yp/helper.dart';
import 'package:yp/router.dart';
import 'package:get/get.dart';

import 'logic.dart';
import 'state.dart';

class CommoditySearchPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CommoditySearchPage();
  }
}

class _CommoditySearchPage extends State<CommoditySearchPage> {
  final CommoditySearchLogic logic = Get.put(CommoditySearchLogic());
  final CommoditySearchState state = Get.find<CommoditySearchLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF7F7F7),
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: Color(0xffEA5504),
        title: Text(
          '商品搜索',
          style: TextStyle(
            color: Colors.white,
            fontSize: 17,
          ),
        ),
        iconTheme: IconThemeData(
          color: Colors.white, //修改颜色
        ),
      ),
      body: GetBuilder<CommoditySearchLogic>(
        builder: (logic) {
          return Container(
            child: Stack(
              children: [
                SingleChildScrollView(
                  child: Column(
                    children: [
                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.only(left: 10, top: 5, bottom: 5),
                        child: Row(
                          children: [
                            Expanded(
                              child: Container(
                                height: setWidth(56),
                                child: TextField(
                                  controller: state.contentTextController,
                                  focusNode: state.contentFocusNode,
                                  maxLines: 1,
                                  style: TextStyle(
                                    color: Color(0xff222222),
                                    fontSize: 14,
                                  ),
                                  decoration: InputDecoration(
                                    contentPadding: EdgeInsets.all(0),
                                    hintText: state.keyword.isEmpty
                                        ? '请输入店内商品名称'
                                        : state.keyword,
                                    hintStyle: TextStyle(
                                      color: Color(0xffcccccc),
                                      fontSize: 14,
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                      // 设置输入框可编辑时的边框样式
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(90)), // 设置边框四个角的弧度
                                      borderSide: BorderSide(
                                        // 用来配置边框的样式
                                        color: Color(0xffEA5504), // 设置边框的颜色
                                        width: setWidth(2), // 设置边框的粗细
                                      ),
                                    ),
                                    focusedBorder: OutlineInputBorder(
                                      // 用来配置输入框获取焦点时的颜色
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(90)), // 设置边框四个角的弧度
                                      borderSide: BorderSide(
                                        // 用来配置边框的样式
                                        color: Color(0xffEA5504), // 设置边框的颜色
                                        width: setWidth(2), // 设置边框的粗细
                                      ),
                                    ),
                                    prefixIcon: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Container(
                                          margin:
                                              const EdgeInsets.only(right: 5),
                                          decoration: BoxDecoration(
                                            border: Border(
                                                right: BorderSide(
                                                    color: const Color(
                                                        0xffD8D8D8))),
                                          ),
                                          child: InkWell(
                                            onTap: () {
                                              logic.changeSearchType(
                                                  state.searchType);
                                            },
                                            child: Row(
                                              children: [
                                                SizedBox(width: 10),
                                                Text(
                                                  state.searchTypeList[state
                                                      .searchType]['title'],
                                                  style: TextStyle(
                                                      fontWeight:
                                                          FontWeight.bold,
                                                      fontSize: 13),
                                                ),
                                                Icon(
                                                  Icons.arrow_drop_down,
                                                  color:
                                                      const Color(0xff000000),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                        InkWell(
                                          onTap: () =>
                                              logic.addHistorySearchKeyword(),
                                          child: Container(
                                            width: 10,
                                            decoration: BoxDecoration(
                                              borderRadius: BorderRadius.only(
                                                topLeft: Radius.circular(
                                                    setWidth(28)),
                                                bottomLeft: Radius.circular(
                                                    setWidth(28)),
                                              ),
                                            ),
                                            alignment: Alignment.center,
                                            child: Icon(
                                              Icons.search,
                                              color: Color(0xffcccccc),
                                              size: setWidth(24),
                                            ),
                                          ),
                                        ),
                                        SizedBox(width: 7),
                                      ],
                                    ),
                                    // InkWell(
                                    //   onTap: () => logic.addHistorySearchKeyword(),
                                    //   child: Container(
                                    //     width: 10,
                                    //     decoration: BoxDecoration(
                                    //       borderRadius: BorderRadius.only(
                                    //         topLeft: Radius.circular(setWidth(28)),
                                    //         bottomLeft:
                                    //             Radius.circular(setWidth(28)),
                                    //       ),
                                    //     ),
                                    //     alignment: Alignment.center,
                                    //     child: Icon(
                                    //       Icons.search,
                                    //       color: Color(0xffcccccc),
                                    //       size: setWidth(24),
                                    //     ),
                                    //   ),
                                    // ),
                                  ),
                                  onSubmitted: (value) {
                                    String text = value.trim();
                                    if(text.isEmpty){
                                      state.contentTextController.text = state.keyword;
                                    }
                                    if (state.contentTextController.text.isEmpty) {
                                      toast('关键字不能为空');
                                      return;
                                    }
                                    logic.addHistorySearchKeyword();

                                    Get.toNamed(
                                            state.searchType == 0
                                                ? RouteConfig
                                                    .commodityKeywordSearch
                                                : RouteConfig.shopSearch,
                                            arguments: value)
                                        .then((value) {
                                      logic.cancelSearch();
                                    });
                                  },
                                ),
                              ),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: TextButton(
                                child: Text(
                                  '取消',
                                  style: TextStyle(
                                    color: Color(0xff666666),
                                    fontSize: 14,
                                  ),
                                ),
                                onPressed: () => Get.back(),
                                // onPressed: () {
                                //   if (state.contentTextController.text.trim().isEmpty) {
                                //     toast('关键字不能为空');
                                //     return;
                                //   }
                                //   logic.addHistorySearchKeyword();
                                //               Get.toNamed(
                                //                 state.searchType == 0
                                //     ? RouteConfig.commodityKeywordSearch
                                //     : RouteConfig.shopSearch,
                                // arguments: state.contentTextController.text)
                                //       .then((value) {
                                //     logic.cancelSearch();
                                //   });
                                // },
                              ),
                            ),
                          ],
                        ),
                      ),
                      Column(
                        children: [
                          Visibility(
                            visible:
                                logic.state.historicalSearchList.length > 0,
                            child: Container(
                              color: Colors.white,
                              child: Column(
                                children: [
                                  Container(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 10),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(bottom: 10),
                                          child: Text(
                                            '历史搜索',
                                            style: TextStyle(
                                                color: Color(0xff666666),
                                                fontSize: 14,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ),
                                        InkWell(
                                          onTap: () => logic
                                              .removeHistorySearchKeyword(),
                                          child: Container(
                                            width: setWidth(80),
                                            height: setWidth(80),
                                            // color: Colors.red,
                                            alignment: Alignment.centerRight,
                                            child: Image.asset(
                                              'assets/images/litterBasket_image.png',
                                              width: setWidth(34),
                                              height: setWidth(34),
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    margin:
                                        EdgeInsets.symmetric(horizontal: 10),
                                    alignment: Alignment.topLeft,
                                    child: Wrap(
                                      direction: Axis.horizontal,
                                      spacing: setWidth(16),
                                      runSpacing: setWidth(20),
                                      children: logic.state.historicalSearchList
                                          .asMap()
                                          .map((key, value) {
                                            return MapEntry(
                                                key,
                                                _historicalSearchWidget(
                                                    index: key,
                                                    hotWord: value));
                                          })
                                          .values
                                          .toList(),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 10),
                                    height: 10,
                                    color: Color(0xffF7F7F7),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Visibility(
                            visible: logic.state.realTimeSearchList.length > 0,
                            child: Container(
                              color: Colors.white,
                              child: Column(
                                children: [
                                  // Container(
                                  //   margin: EdgeInsets.only(bottom: 10.0),
                                  //   child: Image.asset(
                                  //     'assets/images/bannerbg1.png',
                                  //     fit: BoxFit.cover,
                                  //   ),
                                  // ),
                                  Container(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 10),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(bottom: 10),
                                          child: Text(
                                            '实时热搜',
                                            style: TextStyle(
                                                color: Color(0xff666666),
                                                fontSize: 14,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ),
                                        InkWell(
                                          onTap: () => logic
                                              .getRealTimeHotSearchList(true),
                                          child: Container(
                                            width: setWidth(80),
                                            alignment: Alignment.centerRight,
                                            child: Image.asset(
                                              'assets/images/refresh_image.png',
                                              width: setWidth(30),
                                              height: setWidth(30),
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    margin:
                                        EdgeInsets.symmetric(horizontal: 10),
                                    alignment: Alignment.topLeft,
                                    child: Wrap(
                                      direction: Axis.horizontal,
                                      spacing: setWidth(16),
                                      runSpacing: setWidth(20),
                                      children: logic.state.realTimeSearchList
                                          .asMap()
                                          .map((key, value) {
                                            return MapEntry(
                                                key,
                                                _realTimeSearchWidget(
                                                    index: key,
                                                    hotWord: value));
                                          })
                                          .values
                                          .toList(),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 10),
                                    height: 10,
                                    color: Color(0xffF7F7F7),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Visibility(
                            visible: logic.state.hotSearchList.length > 0,
                            child: Container(
                              color: Colors.white,
                              child: Column(
                                children: [
                                  Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 10, vertical: 10),
                                    child: Row(
                                      children: [
                                        Image.asset(
                                          'assets/images/crown_image.png',
                                          width: setWidth(36),
                                          height: setWidth(32),
                                          fit: BoxFit.cover,
                                        ),
                                        SizedBox(
                                          width: setWidth(12),
                                        ),
                                        Expanded(
                                          child: Text(
                                            '热搜榜单',
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                              color: Color(0xffEA5504),
                                              fontSize: 14,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    child: ListView.separated(
                                        shrinkWrap: true,
                                        physics: NeverScrollableScrollPhysics(),
                                        itemCount:
                                            logic.state.hotSearchList.length,
                                        itemBuilder:
                                            (BuildContext context, int index) {
                                          List<Color> colorList = [
                                            Color(0xFFD6B199),
                                            Color(0xFFD6B199),
                                          ];
                                          if (index == 0) {
                                            colorList = [
                                              Color(0xFFFF3100),
                                              Color(0xFFFF3100),
                                            ];
                                          } else if (index == 1) {
                                            colorList = [
                                              Color(0xFFEA5504),
                                              Color(0xFFFF3100),
                                            ];
                                          } else if (index == 2) {
                                            colorList = [
                                              Color(0xFFFFA902),
                                              Color(0xFFFF3100),
                                            ];
                                          } else {
                                            colorList = [
                                              Color(0xFFD6B199),
                                              Color(0xFFD6B199),
                                            ];
                                          }
                                          return InkWell(
                                            child: Container(
                                              padding: EdgeInsets.symmetric(
                                                  horizontal: 10, vertical: 15),
                                              child: Row(
                                                children: [
                                                  Container(
                                                    width: 15,
                                                    height: 15,
                                                    alignment: Alignment.center,
                                                    decoration: BoxDecoration(
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(3),
                                                        gradient: LinearGradient(
                                                            begin: Alignment
                                                                .topCenter,
                                                            end: Alignment
                                                                .bottomCenter,
                                                            colors: colorList)),
                                                    child: Text(
                                                      "${index + 1}",
                                                      style: TextStyle(
                                                          color: Colors.white,
                                                          fontSize: 10),
                                                    ),
                                                  ),
                                                  Expanded(
                                                    child: Container(
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 8),
                                                      child: Text(
                                                        logic.state
                                                                .hotSearchList[
                                                            index]["title"],
                                                        maxLines: 1,
                                                        overflow: TextOverflow
                                                            .ellipsis,
                                                        softWrap: true,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            onTap: () {
                                              String itemNumId = logic
                                                  .state
                                                  .hotSearchList[index]
                                                      ['default_item_num_id']
                                                  .toString();
                                              String styleNumId = logic
                                                  .state
                                                  .hotSearchList[index]
                                                      ['style_num_id']
                                                  .toString();
                                              String shopId = logic
                                                  .state
                                                  .hotSearchList[index]
                                                      ['shop_num_id']
                                                  .toString();
                                              String cat1Id = logic
                                                  .state
                                                  .hotSearchList[index]
                                                      ['cat1_id']
                                                  .toString();
                                              Get.toNamed(
                                                  RouteConfig.goodsDetail,
                                                  arguments: {
                                                    'itemNumId': itemNumId,
                                                    'styleNumId': styleNumId,
                                                    'shopId': shopId,
                                                    'cat1Id': cat1Id,
                                                    'typeIndex': logic.state
                                                            .hotSearchList[
                                                        index]['is_pre_sale']
                                                  });
                                            },
                                          );
                                        },
                                        separatorBuilder:
                                            (BuildContext context, int index) {
                                          return Divider(
                                              height: 1,
                                              indent: 10,
                                              endIndent: 10);
                                        }),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                state.showSearchList
                    ? Positioned(
                        top: 50,
                        left: 10,
                        child: Container(
                          decoration: BoxDecoration(
                            color: Color.fromRGBO(0, 0, 0, .7),
                            borderRadius: BorderRadius.circular(6),
                          ),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: List.generate(
                              state.searchTypeList.length,
                              (index) => InkWell(
                                onTap: () {
                                  logic.changeSearchType(index);
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 17, vertical: 12),
                                  decoration: BoxDecoration(
                                    border: Border(
                                      top: index == 0
                                          ? BorderSide.none
                                          : BorderSide(
                                              color: const Color(0xffffffff)),
                                    ),
                                  ),
                                  child:
                                      Text(state.searchTypeList[index]['title'],
                                          style: TextStyle(
                                            color: index == state.searchType
                                                ? EsColors.Primary
                                                : const Color(0xffffffff),
                                          )),
                                ),
                              ),
                            ),
                          ),
                        ),
                      )
                    : SizedBox(),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 历史搜索 item
  Widget _historicalSearchWidget({int index, String hotWord}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        InkWell(
          onTap: () {
            logic.addHistorySearchKeyword(hotWord: hotWord);
            Get.toNamed(
                    state.searchType == 0
                        ? RouteConfig.commodityKeywordSearch
                        : RouteConfig.shopSearch,
                    arguments: hotWord)
                .then((value) {
              logic.cancelSearch();
            });
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: setWidth(20)),
            height: setWidth(48),
            decoration: BoxDecoration(
              color: Color(0xffEFF0F3),
              borderRadius: BorderRadius.circular(setWidth(24)),
            ),
            alignment: Alignment.center,
            child: Text(
              hotWord,
              style: TextStyle(
                color: Color(0xff666666),
                fontSize: 14,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 实时热搜 item
  Widget _realTimeSearchWidget({int index, Map hotWord}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        InkWell(
          onTap: () {
            logic.addHistorySearchKeyword(hotWord: hotWord["word_name"]);
            Get.toNamed(
                    state.searchType == 0
                        ? RouteConfig.commodityKeywordSearch
                        : RouteConfig.shopSearch,
                    arguments: hotWord["word_name"])
                .then((value) {
              logic.cancelSearch();
            });
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: setWidth(20)),
            height: setWidth(48),
            decoration: BoxDecoration(
              color: Color(0xffEFF0F3),
              borderRadius: BorderRadius.circular(setWidth(24)),
            ),
            alignment: Alignment.center,
            child: Text(
              hotWord["word_name"],
              style: TextStyle(
                color: Color(0xff666666),
                fontSize: 14,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
